import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://47.108.92.210:8182/', // url = base url + request url
  timeout: 15000
})
service.interceptors.request.use(
  config => {
    if(config.url!='/login')
      config.headers['Authorization'] = getToken()
    return config
  },
  error => {
    console.log(error) 
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code == 401) {
      removeToken()
      window.location.href= window.location.origin+'/#/login'
      return false
    } else if(res.code==200) {
      return res
    }else{
      Message({
        message: res.msg || '系统错误',
        type: 'error',
        duration:3000
      })
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
